using System.Collections.Generic;
using System.Linq;

using ManageSystemServer.DAO;
using ManageSystemServer.Entity;

namespace ManageSystemServer.Service
{
    public class StudentService : IService
    {
        public string ServiceName => nameof(StudentService);

        //依赖注入
        private readonly ServerContext context;

        public StudentService(ServerContext context)
        {
            this.context = context;
        }

        //查询
        public Student? GetStudentById(int id)
        {
            var res = context.Students.Where(m => m.StudentId == id).FirstOrDefault();
            return res;
        }

        public List<Student> GetAllStudent()
        {
            var res = context.Students.Where(m => m != null).ToList();
            return res;
        }

        public List<Student> GetStudentByName(string name)
        {
            var res = context.Students.Where(m => m.Name != null && m.Name == name).ToList();
            return res;
        }

        public List<Student> GetStudentByMajor(string major)
        {
            var res = context.Students.Where(m => m.Major != null && m.Major == major).ToList();
            return res;
        }
        //增加
        public bool AddStudent(Student stu)
        {
            if (stu == null)
                return false;
            var res = context.Students.Where(m => m.StudentId == stu.StudentId).FirstOrDefault();
            if (res != null)
            {
                return false;
            }
            else
            {
                context.Students.Add(stu);
                context.SaveChanges();
                return true;
            }
        }
        //删除
        public void DeleteStudent(int id)
        {
            var res = context.Students.Where(s => s.StudentId == id).FirstOrDefault();
            if (res != null)
            {
                context.Students.Remove(res);
                context.SaveChanges();
            }
        }
        //修改
        public void ResetStudent(int id, Student stu)
        {
            var res = context.Students.Where(s => s.StudentId == id).FirstOrDefault();
            if (res != null)
            {
                res.Age = stu.Age;
                res.Grade = stu.Grade;
                res.Name = stu.Name;
                res.Major = stu.Major;
                context.SaveChanges();
            }
        }
    }
}
